package com.machine.filling.function.set.versionCheck;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.machine.filling.R;
import com.machine.filling.base.baseMvp.BaseFragment;
import com.machine.filling.function.init.INextFragment;
import com.machine.filling.function.set.SetFragment;
import com.machine.filling.net.ws.response.WsResVersionCheckBean;
import com.machine.filling.util.CustomToast;
import com.machine.filling.util.DownloadUtil;
import com.machine.filling.util.SdkUtils;
import com.machine.filling.util.StringUtil;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2018/2/2 0002.
 *
 * @description
 */
public class VersionCheckFragment extends BaseFragment<VersionCheckContract.Presenter> implements VersionCheckContract.View, View.OnClickListener {
    private static final String TAG = "VersionCheckFragment";
    private INextFragment INextFragment;
    private TextView tv_version_code;
    private TextView tv_content;
    private Button bt_update;
    private Button bt_cancle;
    private String currentVersionCode;
    private String downLoadPath;//下载地址

    /**
     * @param mIntent
     */
    public VersionCheckFragment(Intent mIntent) {
        super(mIntent);
    }

    @Override
    public View initViews() {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.fg_version_check, null);
        tv_version_code = (TextView) view.findViewById(R.id.tv_version_code);
        tv_content = (TextView) view.findViewById(R.id.tv_content);
        bt_update = (Button) view.findViewById(R.id.bt_update);
        bt_cancle = (Button) view.findViewById(R.id.bt_cancle);
        bt_update.setOnClickListener(this);
        bt_cancle.setOnClickListener(this);
        return view;
    }

    @Override
    public void initDatas() {
        currentVersionCode = SdkUtils.getLocalVersionName(mContext);
        tv_version_code.setText("v" + currentVersionCode);
        mPresenter = new VersionCheckPresenter(mContext, this);
        mPresenter.checkVersion();
    }

    public void setINextFragment(INextFragment INextFragment) {
        this.INextFragment = INextFragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_update:
                if (StringUtil.isNullOrEmpty(downLoadPath)) {
                    CustomToast.showToast(mContext, "更新失败");
                } else {
//                    new UpdateManager(getActivity()).showDownloadDialog(downLoadPath, false);
                    showDownLoadDialog(downLoadPath);
                }
                break;
            case R.id.bt_cancle:
                INextFragment.replaceNext(new Intent(), SetFragment.class.getName());
                break;
        }
    }

    @Override
    public void showUpdateApk(WsResVersionCheckBean updateBean) {
        String versionCode = updateBean.getVersionCode();
        if (!currentVersionCode.equalsIgnoreCase(versionCode)) {
            tv_content.setText("有最新版本" + versionCode + ",请点击更新!");
        } else {
            tv_content.setText("已是最新版本" + versionCode);
        }
        downLoadPath = updateBean.getClientUrl();
    }

    private void showDownLoadDialog(String url ) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("更新中...");

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update, null);
        final ProgressBar mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);

        final Dialog mDownloadDialog = builder.create();
        mDownloadDialog.setCancelable(false);
        mDownloadDialog.show();

        DownloadUtil.get().download(url, "download", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.d(TAG, "onDownloadSuccess() returned: " + "下载完成");
                mDownloadDialog.dismiss();
                installApk();
            }
            @Override
            public void onDownloading(int progress) {
                Log.d(TAG, "onDownloadSuccess() returned: " + "下载中" + progress);
                mProgress.setProgress(progress);
            }
            @Override
            public void onDownloadFailed() {
                Log.d(TAG, "onDownloadFailed() returned: " + "下载失败");
                CustomToast.showToast(mContext,"下载失败");
                mDownloadDialog.dismiss();
            }
        });
    }

    /**
     * 安装
     */
    private void installApk() {
        String installPath;
        // 获得存储卡的路径
        String sdpath = Environment.getExternalStorageDirectory() + "/";
        String sdStatus = Environment.getExternalStorageState();
        if (sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            installPath = sdpath + "download/";
        } else {// 否则存储在手机中
            installPath = "/udisk/download/";
        }

        //如果安装不上可能是签名不一样
        File apkfile = new File(installPath,"client.apk");
        if (!apkfile.exists()) {
            try {
                apkfile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
}
